package com.cqut.service.impl;

import com.cqut.VO.course.CourseDetailsVO;
import com.cqut.VO.course.CourseListDisplayVO;
import com.cqut.entity.UserCourse;
import com.cqut.VO.courseMemberInfo.StudentInfoVO;
import com.cqut.VO.courseMemberInfo.TeacherInfoVO;
import com.cqut.entity.Course;
import com.cqut.entity.Task;
import com.cqut.mapper.CheckTaskMapper;
import com.cqut.mapper.CourseMapper;
import com.cqut.mapper.TaskMapper;
import com.cqut.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 冯永龙
 * @since 2021-06-15
 */
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private CheckTaskMapper checkTaskMapper;

    @Override
    public Map<String, List<CourseListDisplayVO>> getCourses(int id, int type) {
        //实现倒叙排序，时间越新的课程排在前面
        Map<String, List<CourseListDisplayVO>> courseMap = new TreeMap<>(Comparator.reverseOrder());
        List<CourseListDisplayVO> courseList = courseMapper.getCourses(id, type);
        for (CourseListDisplayVO course : courseList) {
            String key = course.getSchoolYear() + "-" + course.getTerm();
            //给课程设置班级人员总数和最最近作业
            Integer totalNumber = courseMapper.getStudentNumberByCourseId(course.getId());
            if (totalNumber == null) {
                course.setTotalNumber(0);
            } else {
                course.setTotalNumber(totalNumber);
            }
            List<Task> recentTask = taskMapper.findRecentTask(course.getId());
            course.setRecentTasks(recentTask);
            //如果没有学年信息则插入一个key值，否则在已有的key值列表中加入课程信息
            if (!courseMap.containsKey(key)) {
                courseMap.put(key, new ArrayList<>());
                courseMap.get(key).add(course);
            } else {
                courseMap.get(key).add(course);
            }
            Collections.sort(courseMap.get(key), new Comparator<CourseListDisplayVO>() {
                @Override
                public int compare(CourseListDisplayVO o1, CourseListDisplayVO o2) {
                    if (o1.getSort() > o2.getSort()) {
                        return 1;
                    } else if (o1.getSort() == o2.getSort()) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            });
        }
        return courseMap;
    }


    @Override
    public boolean deleteCourseById(int courseId) {
        if (courseMapper.deleteCourseById(courseId) == 1) {
            courseMapper.deleteUserCourseById(courseId);
            taskMapper.deleteTaskByCourseId(courseId);
            List<String> taskIdList = taskMapper.getTaskIdListByCourseId(courseId);
            for (String taskId : taskIdList) {
                checkTaskMapper.deleteTaskRecord(taskId);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean updateCourse(Course course) {
        if (courseMapper.updateCourse(course) == 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean createCourse(Course course, Integer userId, Integer sort) {
        Random random = new Random();
        int courseId = random.nextInt(100000000);
        course.setId(courseId);
        UUID uuid = UUID.randomUUID();
        String courseCode = uuid.toString().substring(0, 6);
        course.setCourseCode(courseCode.toUpperCase());
        int i = courseMapper.insertCourse(course);
        String enterTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        if (i == 1) {
            courseMapper.addCourse(courseId, userId, 0, enterTime, sort);
            return true;
        }
        return false;
    }


    @Override
    public boolean addCourse(String courseCode, Integer userId, Integer sort) {
        Integer courseId = courseMapper.getCourseIdByCourseCode(courseCode);
        if (courseId == null) {
            return false;
        }

        if (!Objects.isNull(courseMapper.getStudentInCourse(courseId,userId))){
            return false;
        }

        String enterTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        List<String> list = taskMapper.getTaskIdListByCourseId(courseId);
        for (String taskId : list) {
            checkTaskMapper.insertTaskRecord(taskId, userId);
        }


        return courseMapper.addCourse(courseId, userId, 1, enterTime, sort) == 1;
    }

    @Override
    public List<TeacherInfoVO> getTeachTeamList(Integer courseId) {
        return courseMapper.getTeachTeamListByCourseId(courseId);
    }

    @Override
    public List<StudentInfoVO> getStudentList(Integer courseId) {
        return courseMapper.getStudentListByCourseId(courseId);
    }

    @Override
    public boolean updateRankCourse(List<UserCourse> courses) {
        courseMapper.updateRankCourse(courses);
        return true;
    }

    @Override
    public CourseDetailsVO getCourseDetails(Integer courseId) {
        CourseDetailsVO courseDetails = courseMapper.getCourseDetailsByCourseId(courseId);
        int studentNumber = courseMapper.getStudentNumberByCourseId(courseId);
        courseDetails.setTotalNumber(studentNumber);
        return courseDetails;
    }

    @Override
    public boolean quitCourse(Integer courseId, Integer userId) {
        //获取该课程的所有作业id
        List<String> taskIdList = taskMapper.getTaskIdListByCourseId(courseId);
        //删除该学生这门课程的所有作业记录
        for (String taskId : taskIdList) {
            taskMapper.deleteTaskRecordByTaskIdAndUserId(taskId, userId);
        }
        return courseMapper.quitCourseByCourseIdAndUserId(courseId, userId) == 1;
    }
}
